<template>
    <el-container class="question-bank">
        <el-page-header @back="goBack" :content="`${title} - 题库`">
        </el-page-header>
        <div class="question-bank-header">
            <el-button size="small" type="primary" @click="openDialog('add')">新建题目</el-button>

            <input ref="fileInput" type="file" style="display:none" accept=".csv" @change="handleFileChange" />
            <el-button size="small" type="success" style="margin-left:20px" @click="handleUpload">上传题库</el-button>

            <el-button size="small" @click="handleDownloadTemplate">下载模板</el-button>
            <el-button size="small" type="primary" style="margin-left:20px" @click="handleTest">测试导入数据</el-button>
        </div>


        <el-main class="question-bank__content">
            <div ref="container" class="table-container">
                <el-table ref="table" :data="datas" style="width: 100%" align="center" header-align="center">
                    <el-table-column label="序号" prop="index" center width="120px" />
                    <el-table-column label="题干" prop="title" center />
                    <el-table-column label="题目类型" prop="type" width="80px" center />
                    <el-table-column label="选项" center class-name="option-column">
                        <template slot-scope="scope">
                            <div v-for="item in scope.row.options" :key="item.id" class="cell-question">
                                <span>{{ item.label }}</span>
                                <span class="label-value">:</span>
                                <span>{{ item.value }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="正确答案" center>
                        <template slot-scope="scope">
                            <span style="color:#409EFF">{{ scope.row.correctAnswers }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" center width="180px">
                        <template slot-scope="scope">
                            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                            <el-button size="small" @click="openDialog('edit', scope.row)">更改</el-button>
                        </template>
                    </el-table-column>
                </el-table>


            </div>
            <div class="pagination-container">
                <el-pagination :current-page="pageNum" :page-size="pageSize" layout="prev, pager, next" :total="total"
                    background @current-change="handlePageChange" />
            </div>
        </el-main>

        <dialog-edit :visible.sync="dialogVisible" v-if="dialogVisible" @refresh="refresh" ref="edit"></dialog-edit>
    </el-container>
</template>

<script>
import dialogEdit from "./components/edit.vue"
import { questionBankTemplate } from "@/utils/const.js"

export default {
    name: "question-bankList",
    components: {
        dialogEdit
    },
    data() {
        return {
            datas: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            dialogVisible: false,
        };
    },

    computed: {
        title() {
            const { title } = this.$route.query;
            return title;
        },
    },

    created() {
        this.refresh();
    },
    methods: {

        refresh() {
            this.pageNum = 1;
            this.fetchDatas();
        },

        async fetchDatas() {
            const loading = this.$loading();
            try {
                const { lessonId } = this.$route.query;
                const { pageNum, pageSize } = this;

                const { data: { sorts, total } } = await this.$fetch.get("/api/topic-lesson-question-bank/list", {
                    lessonId,
                    pageNum,
                    pageSize
                });
                this.datas = sorts.map((item, index) => {
                    return {
                        ...item,
                        index: index + 1,
                        options: JSON.parse(item.options),
                    }
                });
                this.total = total
                this.$nextTick(() => {
                    const tableBodyWrapper = document.querySelector('.el-table__body-wrapper');
                    if (tableBodyWrapper) {
                        tableBodyWrapper.scrollTop = 0;
                    }
                });;
            } catch (error) {
                console.log(error);
            }
            loading.close();

        },


        openDialog(type, row) {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.$refs.edit.init(type, row);
            })
        },

        handleDelete(row) {
            const params = {
                id: row.id,
            };
            this.$confirm("确定要删除此题目？", "", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确认",
                cancelButtonText: "取消",
            }).then(async () => {
                const { code } = await this.$fetch.post(
                    "/api/topic-lesson-question-bank/delete",
                    params
                );
                if (code === 0) {
                    this.$message.success("删除成功");
                }
                this.refresh();
            });
        },



        handlePageChange(pageNum) {
            this.pageNum = pageNum;
            this.fetchDatas();
        },


        handleFileChange(event) {
            const selectedFile = event.target.files[0];
            if (selectedFile) {
                console.log('选择的文件:', selectedFile.name);
                this.uploadFile(selectedFile);
            } else {
                console.log('没有选择文件');
            }
        },

        async uploadFile(file) {
            const { lessonId } = this.$route.query;
            const Loading = this.$loading({
                lock: true,
                text: '上传中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            try {
                const res = await this.$fetch.upload("/api/topic-lesson-question-bank/createByCsv", {
                    file,
                    lessonId
                })
                if (res.code === 0) {
                    const { success, total } = res.data;
                    this.$message.success(`已成功导入${success.length}个题目, 共${total.length}个题目, 失败${total.length - success.length}题目`);
                    this.refresh();
                } 
            } catch (error) {
                this.$message.error(error.message);
            } finally {
                Loading.close()
            }

        },

        handleUpload() {
            this.$refs.fileInput.value = null;
            this.$nextTick(()=>{
                this.$refs.fileInput.click();
            })
        },

        async handleTest() {

            for (let i = 0; i < 20; i++) {
                let params = this.createMock();
                setTimeout(() => {
                     this.$fetch.post("/api/topic-lesson-question-bank/create", params);
                     if (i === 19) {
                         this.refresh();
                     }
                }, i * 100);
            }
            this.refresh();
        },

        createMock(topicId) {

            const num1 = parseInt(Math.random() * 10) + 1;

            const num2 = parseInt(Math.random() * 10) + 1;

            const arr = ['+', '-', 'x', '÷'];

            const index = parseInt(Math.random() * 4)

            const method = arr[index];

            const title = `${num1} ${method} ${num2} = ？`

            const options = [
                {
                    "label": "A",
                    "value": num1 + num2
                },
                {
                    "label": "B",
                    "value": num1 - num2
                },
                {
                    "label": "C",
                    "value": num1 * num2
                },
                {
                    "label": "D",
                    "value": `${num1} / ${num2}`
                }
            ]

            return {
                topicId,
                title,
                type: "单选题",
                options,
                correctAnswers: options[index].label,
                topicId: this.$route.query.topicId,
                lessonId: this.$route.query.lessonId
            }



        },

        handleDownloadTemplate() {
            window.open(questionBankTemplate);
        },

        goBack() {
            this.$router.go(-1);
        }

    },


};
</script>

<style scoped lang="scss">
.question-bank {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 50px);

    .title {
        font-size: 26px;
        width: 100%;
        line-height: 42px;
        justify-content: center;
        align-items: center;
        display: flex;
    }



    .cell-question {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;


        .label-value {
            margin-left: 4px;
            margin-right: 8px;
        }
    }

    .question-bank-header {
        height: 40px;
        display: flex;
        align-items: center;
        margin-top: 30px;
    }

    .question-bank__content {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: auto;
        padding-bottom: 0;

        .table-container {
            flex: 1;
            overflow: hidden;
        }
    }

    .pagination-container {
        display: flex;
        justify-content: center;
        padding: 20px 0;

        .el-pagination {
            padding: 20px 0;
        }
    }

    .option-item {
        display: flex;
        margin-bottom: 4px;

        .label {
            margin-right: 4px;
        }

        .value {
            margin-right: 4px;
        }
    }
}

::v-deep .el-table {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-table__row {
        td.option-column {
            flex-direction: column;
        }
    }

    .cell {
        display: flex;
    }

    .el-table__body-wrapper {
        overflow-y: auto;
        flex: 1;
        border-top: 1px solid #EBEEF5;
    }

    .option-column {
        .cell {
            display: flex;
            text-align: center;
            flex-direction: column !important;
        }
    }
}
</style>

<style lang="less">
.el-table--enable-row-transition .el-table__body td.option-column {
    .cell {
        flex-direction: column;

    }
}
</style>